<?php

namespace App\Admin\Controllers\DataView;

use App\Models\UserAddRmb;
use App\Models\UserLogin;

use App\Models\UserLogoutHs;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Callout;
use Encore\Admin\Widgets\Chart\Bar;
use Encore\Admin\Widgets\Chart\Line;
use Encore\Admin\Widgets\Chart\Pie;
use Encore\Admin\Widgets\Collapse;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;

class OperationController extends Controller
{
    use ModelForm;
    private $userLogin;
    private $userLogoutHs;
    private $userAddRmb;

    public function __construct(UserLogin $userLogin,
                                UserAddRmb $userAddRmb,
                                UserLogoutHs $userLogoutHs)
    {
        $this->userLogin = $userLogin;
        $this->userAddRmb = $userAddRmb;
        $this->userLogoutHs = $userLogoutHs;
        parent::__construct();
    }

    /**
     * 运营数据统计 -- 充值数据
     * @param Request $request
     * @return mixed
     */
    public function recharge(Request $request)
    {
        $date = $request->get('date') ?: date('Y-m-d');
        $config = config('admin.data.operation.recharge');
        $servers = $this->userLogin->getServers(date('Ym', strtotime($date)));
        $server = $request->get('server', 2);

        return Admin::content(function (Content $content) use ($config, $date, $servers, $server) {
            $content->header($config['label']);
            $content->description($date . " 服务区:" . $servers[ $server ]);
            $content->row(function (Row $row) use ($config, $date, $servers, $server) {

                $date = strtotime($date);

                // 每日充值排行
                $headers = ['', '用户id', '充值金额'];
                $rows = $this->userAddRmb->getDayRechargeAmountsGroupByUser(strtotime('20170508'), $servers[ $server ]);
                $table = new Table($headers, $rows);

                $row->column(3, function (Column $column) use ($table) {
                    $column->append((new Box('每日充值排行', $table))->style('primary')->solid());
                });

                // 充值时间分布曲线
                $charges = $this->userAddRmb->getDayRechargeAmountsPerHours($date, $servers[ $server ]);
                $data = [
                    'labels'   => config('admin.data.hours'),
                    'datasets' => [[
                        'label'     => $servers[ $server ],
                        'fillColor' => "rgba(151,187,205,0.2)",
                        'data'      => $charges,
                    ]],
                ];
                $row->column(6, function (Column $column) use ($data) {
                    $column->append((new Box('充值时间分布曲线', new Line($data)))->style('primary')->solid());
                });

                // 查询条件表单
                $row->column(3, function (Column $column) use ($date, $servers, $server) {
                    $form = new Form();
                    $form->select('server', '区服')->options($servers)->default($server);
                    $form->date('date', '日期')->default(date('Y-m-d', $date));
                    $form->method('post');
                    $form->action(admin_url('dataView/operationalDataRecharge'));
                    // $form->disablePjax();
                    $column->append((new Box('按日期查询', $form))->style('primary')->solid());
                });

            });
        });
    }

    /**
     * 运营数据统计 -- 用户在线及时长
     * @param Request $request
     * @return mixed
     */
    public function online(Request $request)
    {
        $date_start = $request->get('date_start') ?: date('Y-m-d');
        $date_end = $request->get('date_end') ?: date('Y-m-d');
        $date = $request->get('date') ?: date('Y-m-d');
        $config = config('admin.data.operation.online');
        $servers = $this->userLogin->getServers(date('Ym', strtotime($date)));
        $server = $request->get('server', 2);

        $params = [
            'type'        => $request->get('type', 'date'),
            'date'        => $date,
            'date_start'  => $date_start,
            'date_end'    => $date_end,
            'servers'     => $servers,
            'server'      => $server,
            'server_name' => $servers[ $server ],
        ];

        return Admin::content(function (Content $content) use ($config, $params) {
            $content->header($config['label']);
            $content->description(($params['type'] === 'date' ? $params['date'] : $params['date_start'] . ' ~ ' . $params['date_end']) . " 服务区:" . $params['server_name']);
            $content->row(function (Row $row) use ($config, $params) {
                $date = strtotime($params['date']);
                // 每日在线时长分布比例

                if ($params['type'] === 'date') {
                    // 每日在线人数分布
                    $charges = $this->userLogin->getDayOnlineUsersPerHours($date, $params['server_name']);
                    $data = [
                        'labels'   => config('admin.data.hours'),
                        'datasets' => [[
                            'label'     => $params['server_name'],
                            'fillColor' => "rgba(151,187,205,0.2)",
                            'data'      => $charges,
                        ]],
                    ];
                    $row->column(7, function (Column $column) use ($data) {
                        $column->append((new Box('每日在线人数分布', new Line($data)))->style('primary')->solid());
                    });
                } else {
                    $dateRange = $this->getDateFromRange($params['date_start'], $params['date_end']);
                    $logouts = [];
                    $conditoin = ['<=10' => '<=10M', '<=60' => '<=1H', '<=240' => '<=4H', '<=360' => '<=6H', '<=720' => '<=12H', '>720' => '>12H'];
                    $headers = array_merge(['Date'], config('admin.data.hours'));
                    $rows = [];
                    $logoutsRows = [];
                    foreach ($dateRange as $d) {
                        $d = strtotime($d);
                        $getDayOnlineUsersPerHours = $this->userLogin->getDayOnlineUsersPerHours($d, $params['server_name']);
                        if(array_sum($getDayOnlineUsersPerHours)) {
                            $rows[] = array_merge([date('Ymd', $d)], $getDayOnlineUsersPerHours);
                        }
                        $logouts = $this->userLogoutHs->getOnlineTimes($d, $params['server_name']);
                        if($logouts) {
                            $logoutsRows[] = [
                                date('Ymd', $d),
                                isset($logouts['<=10']) ? $logouts['<=10'] : 0,
                                isset($logouts['<=60']) ? $logouts['<=60'] : 0,
                                isset($logouts['<=240']) ? $logouts['<=240'] : 0,
                                isset($logouts['<=360']) ? $logouts['<=360'] : 0,
                                isset($logouts['<=720']) ? $logouts['<=720'] : 0,
                                isset($logouts['>720']) ? $logouts['>720'] : 0,
                            ];
                        }
                    }
                    $table1 = new Table($headers, $rows);
                    $table1->id('paginate')->paginate();
                    $table2 = new Table(array_merge(['Date'], $conditoin), $logoutsRows);
                    $table2->id('paginate2')->paginate();
                    $tab = new Tab();
                    $tab->add('每日在线人数分布', $table1);
                    $tab->add('每日在线人数分布', $table2);
                    $row->column(7, function (Column $column) use ($tab) {
                        $column->append((new Box('用户在线时长统计', $tab))->style('primary')->solid());
                    });
                }


                // 查询条件表单
                $row->column(5, function (Column $column) use ($date, $params) {

                    $form1 = new Form();
                    $form1->select('server', '区服')->options($params['servers'])->default($params['server']);
                    $form1->date('date', '日期')->default(date('Y-m-d', $date));
                    $form1->hidden('type')->default('date');
                    $form1->method('post');
                    $form1->action(admin_url('dataView/operationalDataOnline'));
                    // $form->disablePjax();

                    $form2 = new Form();
                    $form2->select('server', '区服')->options($params['servers'])->default($params['server']);
                    $form2->hidden('type')->default('dateRage');
                    $form2->dateRange('date_start', 'date_end', '日期范围')->default(date('Y-m-d', $date));
                    $form2->method('post');
                    $form2->action(admin_url('dataView/operationalDataOnline'));
                    // $form->disablePjax();
                    $tab = new Tab();
                    if ($params['type'] === 'date') {
                        $tab->add('按日期查询', $form1);
                        $tab->add('按日期范围查询', $form2);
                    } else {
                        $tab->add('按日期范围查询', $form2);
                        $tab->add('按日期查询', $form1);
                    }

                    $column->append((new Box('查询', $tab))->style('primary')->solid());
                });

                if ($params['type'] === 'date') {
                    $logouts = $this->userLogoutHs->getOnlineTimes($date, $params['server_name']);
                    $pie = new Pie([
                        ['≤10M', isset($logouts['<=10']) ? $logouts['<=10'] : 0],
                        ['≤1H', isset($logouts['<=60']) ? $logouts['<=60'] : 0],
                        ['≤4H', isset($logouts['<=240']) ? $logouts['<=240'] : 0],
                        ['≤6H', isset($logouts['<=360']) ? $logouts['<=360'] : 0],
                        ['≤12H', isset($logouts['<=720']) ? $logouts['<=720'] : 0],
                        ['>12H', isset($logouts['>720']) ? $logouts['>720'] : 0],
                    ]);
                    $row->column(7, function (Column $column) use ($pie) {
                        $column->append((new Box('每日在线时长分布比例', $pie))->style('primary')->solid());
                    });

                    $row->column(3, function (Column $column) use ($logouts) {
                        // $form->disablePjax();
                        $headers = [' ', '人数', '占比'];
                        $rows = [];
                        $conditoin = ['<=10' => '<=10M', '<=60' => '<=1H', '<=240' => '<=4H', '<=360' => '<=6H', '<=720' => '<=12H', '>720' => '>12H'];
                        foreach ($conditoin as $key => $value) {
                            $total = array_sum($logouts);
                            $conditoin = htmlentities($value);
                            $num = isset($logouts[ $key ]) ? $logouts[ $key ] : 0;
                            $rows[] = [$conditoin, $num, $total ? (round($num / $total, 4) * 100) . "%" : '0%'];
                        }
                        $column->append((new Box('每日在线时长分布', new Table($headers, $rows)))->style('primary')->solid());
                    });
                }
            });
        });
    }


    /**
     * 运营数据统计 -- 用户注册统计
     * @param Request $request
     * @return mixed
     */
    public function registered(Request $request)
    {
        $date = $request->get('date') ?: date('Y-m-d');
        $config = config('admin.data.operation.registered');
        $servers = $this->userLogin->getServers(date('Ym', strtotime($date)));
        $server = $request->get('server', 2);

        return Admin::content(function (Content $content) use ($config, $date, $servers, $server) {
            $content->header($config['label']);
            $content->description($date . " 服务区:" . $servers[ $server ]);

            $content->row(function (Row $row) use ($config, $date, $servers, $server) {
                // 每日、每小时注册人数
                $data_registered = $this->getRegisteredUsersPerHoursByDate($date);
                // 每日、每小时创角人数
                $date = strtotime($date);
                $data_createdRoles = $this->userLogin->getDayCreatedRoleUsersPerHours($date, $servers[ $server ]);

                $hours = config('admin.data.hours');
                $headers = array_merge(['Hours'], $hours, ['总计']);
                $rate = [];
                foreach ($hours as $h) {
                    $data_registered[ $h ] = isset($data_registered[ $h ]) ? $data_registered[ $h ] : 0;
                    $data_createdRoles[ $h ] = isset($data_createdRoles[ $h ]) ? $data_createdRoles[ $h ] : 0;
                    $rate[ $h ] = isset($data_registered[ $h ]) && $data_registered[ $h ] ? round($data_createdRoles[ $h ] / $data_registered[ $h ], 4) * 100 . "%" : 0;
                }
                $rate['24'] = $data_registered['24'] ? round($data_createdRoles['24'] / $data_registered['24'], 4) * 100 . "%" : 0;
                ksort($data_registered);
                ksort($data_createdRoles);

                $rows = [
                    array_merge(['注册数'], $data_registered),
                    array_merge(['创角数'], $data_createdRoles),
                    array_merge(['转化率'], $rate),
                ];
                $table = new Table($headers, $rows);

                $row->column(9, function (Column $column) use ($table) {
                    $box = new Box();
                    $box->title('用户每日注册/创角数据');
                    $box->content('<div class="table-responsive">' . $table . '</div>');
                    $column->append($box->style('primary')->solid());
                });

                // 查询条件表单
                $row->column(3, function (Column $column) use ($date, $servers, $server) {
                    $form = new Form();
                    $form->select('server', '区服')->options($servers)->default($server);
                    $form->date('date', '日期')->default(date('Y-m-d', $date));
                    $form->method('post');
                    $form->action(admin_url('dataView/operationalDataRegistered'));
                    // $form->disablePjax();
                    $column->append((new Box('按日期查询', $form))->style('primary')->solid());
                });

            });
        });
    }

    /**
     * 运营数据统计 -- 用户留存统计
     * @param Request $request
     * @return mixed
     */
    public function retained(Request $request)
    {
        $date_start = $request->get('date_start') ?: date('Y-m-d');
        $date_end = $request->get('date_end') ?: date('Y-m-d');
        $config = config('admin.data.operation.retained');
        $servers = $this->userLogin->getServers(date('Ym', strtotime($date_start)));
        $server = $request->get('server', 2);


        return Admin::content(function (Content $content) use ($config, $date_start, $date_end, $servers, $server) {
            $content->header($config['label']);
            $content->description($date_start . ' ~ ' . $date_end . " 服务区:" . $servers[ $server ]);
            $content->row(function (Row $row) use ($config, $date_start, $date_end, $servers, $server) {

                $dateRange = $this->getDateFromRange($date_start, $date_end);
                $rows = [];
                if (strtotime($date_end) >= strtotime(date('Y-m-d') . "+1 day")) {
                    $row->column(12, function (Column $column) {
                        $column->append((new Callout('查询结束日期不得大于今天日期'))->style('warning'));
                    });
                } else {
                    foreach ($dateRange as $d) {
                        $date = strtotime($d);
                        $data = $this->userLogin->getRetainedUsersByDate($date, $servers[ $server ]);
                        if(array_sum($data)) {
                            $rows[] = array_merge([$d], $data);
                        }
                    }
                }
                $headers = config('admin.data.operation.retained.condition');
//                print_r($rows);
                $table = new Table($headers, $rows);
                $table->id('paginate')->paginate();

                $title = '用户留存率 ' . $date_start . ' ~ ' . $date_end . " 服务区:" . $servers[ $server ];
                $row->column(8, function (Column $column) use ($table, $title) {
                    $box = new Box();
                    $box->title($title);
                    $box->content('<div class="table-responsive">' . $table . '</div>');
                    $column->append($box->style('primary')->solid());
                });

                // 查询条件表单
                $row->column(4, function (Column $column) use ($date_start, $date_end, $servers, $server) {
                    $form = new Form();
                    $form->select('server', '区服')->options($servers)->attribute('required')->default($server);
                    $form->dateRange('date_start', 'date_end', '日期范围')->attribute('required');
                    $form->method('post');
                    $form->action(admin_url('dataView/operationalDataRetained'));
                    // $form->disablePjax();
                    $column->append((new Box('按日期查询', $form))->style('primary')->solid());
                });

            });
        });
    }

    /**
     * 根据日期从97time_uc获得日每小时注册人数
     * @param $date
     * @return array
     */
    public function getRegisteredUsersPerHoursByDate($date)
    {
        $api_uri = "http://www.97time.com/adminlog.php/Index/getRegisteredUsersPerHoursByDate?date=" . $date;
        $data = json_decode(file_get_contents($api_uri), true);

        $res = [];
        foreach ($data as $value) {
            $res[ $value['hour'] ] = (int)$value['amounts'];
        }
        $res['24'] = array_sum($res);

        return $res;
    }


}
